<template>
	<view class="search-record-components" :style="[wrapStyle]" v-if="show">
		<view class="title-wrap">
			<text class="label-text">搜索历史</text>
			<view class="clear-button click" @click="handleClear">清除历史记录</view>
		</view>
		<view class="list-wrap">
			<u-tag
				closeable
				class="u-tag"
				:text="content"
				mode="dark"
				type="success"
				font-size="30"
				color="#333333"
				bg-color="#f8f8f8"
				:key="index"
				v-for="(content, index) in records"
				@click="handleClick(content)"
				@close="handleDelete(index)"
			/>
		</view>
	</view>
</template>

<script>
import mixins from '@/mixins/components.js';
export default {
	name: 'search-record',
	mixins: [mixins],
	props: {
		show: {
			type: Boolean,
			default: true
		},
		storageName: {
			type: String,
			default: 'searchs'
		},
		max :{
			type: [Number,String],
			default: 6
		},
	},
	data() {
		return {
			records: []
		};
	},
	created() {
		this.handleInit();
	},
	methods: {
		// 初始化
		handleInit(){
			let records = uni.getStorageSync(this.storageName);
			if(records.length){
				this.records = records;
			}
		},
		// 点击记录
		handleClick(val){
			this.$emit('click',val);
		},
		// 删除当前搜索记录
		handleDelete(index) {
			let val = this.records[index];
			this.$emit('delete',val);
			this.records.splice(index,1);
			uni.setStorageSync(this.storageName, this.records);
		},
		// 删除全部搜索记录
		handleClear(){
			this.$confirm('确认删除全部搜索记录?','提示',() => {
				this.records = [];
				uni.setStorageSync(this.storageName, this.records);
				this.$emit('clear');
			})
		},
		add(val){
			this.records.forEach((record,index) => {
				if(record == val) this.records.splice(index,1);
			})
			this.records.unshift(val);
			if (this.records.length > this.max) {
				this.records.pop();
			}
			uni.setStorageSync(this.storageName, this.records);
		}
	},
};
</script>

<style scoped lang="scss">
.search-record-components {
	display: flex;
	flex-direction: column;
	.title-wrap {
		display: flex;
		font-size: 28rpx;
		align-items: center;
		margin-bottom: 20rpx;
		justify-content: space-between;
		.clear-button {
			color: $primary-color;
		}
	}
	.list-wrap {
		display: flex;
		flex-wrap: wrap;
		.u-tag {
			margin-right: 20rpx;
			margin-bottom: 20rpx;
		}
	}
}
</style>
